from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from unicodedata import category

from course import courseser
from course.models import CourseModel
from home import models,homeser


# Create your views here.

# 顶部导航
class TopNav(APIView):
    def get(self, request):
        topnav =models.NavModel.objects.filter(is_delete=False,position=True).order_by('order')#position是是否是顶部还是底部
        ser =homeser.NavSer(topnav,many=True)
        return Response({"msg": "ok", "code": 200, 'data': ser.data})
#底部导航
class FootNav(APIView):
    def get(self, request):
        footnav =models.NavModel.objects.filter(is_delete=False,position=False).order_by('order')
        ser =homeser.NavSer(footnav,many=True)
        return Response({"msg": "ok", "code": 200, 'data': ser.data})
# banner 轮播图
class Banner(APIView):
    def get(self, request):
        benner = models.BannerModel.objects.filter(is_delete=False).order_by('order')
        ser =homeser.BannerSer(benner,many=True)
        return Response({"msg": "ok", "code": 200, 'data': ser.data})


# 分类 一级分类 父分类
class Category(APIView):
    def get(self, request):
        category = models.CategoryModel.objects.filter(is_delete=False,parent=None).order_by('order')
        ser =homeser.CategorySer(category,many=True)
        for i in ser.data:
            i['children']=i['children'][:3]
        return Response({"msg": "ok", "code": 200, 'data': ser.data})

# 父级分类的子分类，获取子分类数据
class Nowcate(APIView):
    def get(self, request):
        # 拿到结果集 是id,is_delete,is_home，...   chilrden :0{id,catename} 1{}  2{}......各种字段组合的结果集
        nowcate=models.CategoryModel.objects.filter(is_delete=False,id=request.query_params.get('id')).first()
        # print(nowcate)
        # 对结果集进行序列化
        # print(ser.data)
        # {'id': 3, 'children': [{'id': 12, 'catename': 'Flutter'}, {'id': 13, 'catename': ' Android'}, {'id': 14, 'catename': 'iOS'}], 'is_delete': False, 'create_time': '2024-11-21T05:35:34.306278Z', 'order': 1, 'catename': '移动开发', 'is_home': False, 'is_hot': False, 'is_good': False, 'parent': None}
        ser =homeser.CategorySer(nowcate)


        # 根据一级id获取到二级分类的id，[1,2,3,4] 用in 拿到对应的课程信息
        # categorymodle 是分类的模型 allcate是所有的二级分类
        allcate =models.CategoryModel.objects.filter(is_delete=False,parent=request.query_params.get('id'))

        catelist =[]
        for i in allcate:
            catelist.append(i.id)
        #     根据二级分类获取三级 课程信息
        # print(catelist)
        allcourse =CourseModel.objects.filter(is_delete=False,category__in=catelist,ishome=True).order_by('order')
        # 课程的序列化
        ser2 = courseser.CourseSer(allcourse,many=True)
        mydata = ser.data
        # 只要前四条数据
        mydata["course"] =ser2.data[:4]
        return Response({"msg": "ok", "code": 200, 'data': mydata})
